/*
 * Copyright 2010 Alessandro Bellucci
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.soupframework.gwt.designerpanel.client.command.impl;

import java.util.ArrayList;
import java.util.List;

import org.soupframework.gwt.designerpanel.client.designer.ContainerDesigner;
import org.soupframework.gwt.designerpanel.client.designer.Designer;
import org.soupframework.gwt.designerpanel.client.util.Util;

public class ContainerRemoveObjectCommand<T> extends ContainerDesignerCommandBase<T> {

	private T object;
	private Designer<T> d;
	private Integer left;
	private Integer top;
	private List<ContainerClearCommand<T>> childrenClearCommands = new ArrayList<ContainerClearCommand<T>>();

	@SuppressWarnings("unchecked")
	ContainerRemoveObjectCommand(ContainerDesigner<T> designer, T object) {
		super(designer);

		this.d = this.getDesigner().getChildDesigner(object);
		if(this.d != null) {
			if(this.d instanceof ContainerDesigner){
				ContainerClearCommand clearCommand = new ContainerClearCommand((ContainerDesigner)this.d);
				this.childrenClearCommands.add(clearCommand);
			}
		}
		this.object = object;
		this.left = Util.getWidgetStyleLeft(designer.getChildObjectView(object));
		this.top = Util.getWidgetStyleTop(designer.getChildObjectView(object));
	}

	@Override
	protected void doCommandInt() {
		for(ContainerClearCommand<T> clearCommand : this.childrenClearCommands){
			clearCommand.doCommand();
		}
		this.getDesigner().getOperations().removeObject(this.object);
	}

	@Override
	protected void undoCommandInt() {
		for(ContainerClearCommand<T> clearCommand : this.childrenClearCommands){
			clearCommand.undoCommand();
		}
		this.getDesigner().getOperations().addObject(this.object, this.left != null ? this.left : 0, this.top != null ? this.top : 0);
		if(this.d != null){
			this.getDesigner().addChildDesigner(this.d);
		}
	}
}
